﻿// 开发者:micropu
// 公司:佛山远钧智慧科技有限公司

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace Admin.NET.Application;


/// <summary>
/// 双发固件接口
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class firmwareInterface : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Device> _deviceRep;
    private readonly SqlSugarRepository<Employee> _employeeRep;
    private readonly SqlSugarRepository<UploadLog> _uploadLogRep;
    private readonly ZJLog zJLog;

    public firmwareInterface(SqlSugarRepository<Device> deviceRep, SqlSugarRepository<Employee> employeeRep, ZJLog zJLog, SqlSugarRepository<UploadLog> uploadLogRep)
    {
        _deviceRep = deviceRep;
        _employeeRep = employeeRep;
        this.zJLog = zJLog;
        _uploadLogRep = uploadLogRep;
    }

    /// <summary>
    /// 接收人员数据
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("other/EmpRev")]
    [AllowAnonymous]
    public async Task<dynamic> EmpRev(EmpRec data)
    {
        if (string.IsNullOrWhiteSpace(data.EmpID)) throw Oops.Oh("人员ID不能为空");
        if (string.IsNullOrWhiteSpace(data.ClientSn)) throw Oops.Oh("设备ID不能为空");
        var device = await _deviceRep.GetFirstAsync(u => u.ClientSn == data.ClientSn) ?? throw Oops.Oh(ErrorCodeEnum.D1002);

        //查找数据库中是否存在此记录
        var persons = await _employeeRep.AsQueryable()
            .Where(u => u.ZjEmpID == data.EmpID && u.ProjectId == device.ProjectId)
            .ClearFilter()
            .FirstAsync();
        if (persons == null) //新增
        {
            var newEmp = new Employee
            {
                ProjectId = device.ProjectId,
                TenantId = device.TenantId,
                CreateOrgId = device.CreateOrgId,
                ZjEmpID = data.EmpID,
                Name = data.Name,
                Facephoto = data.ImageBase64,
                IdNum = data.IdNum,
            };
            await _employeeRep.InsertAsync(newEmp);
            await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"收到双发固件人员信息:{data.Name}", data.ClientSn, 0, 0, 0, "");
            return "接收正常";
        }
        await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"收到双发固件人员信息:{data.Name}时发生异常", data.ClientSn, 0, 0, 0, "");
        return "接收异常";
    }


    /// <summary>
    /// 通行数据接收
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("other/LogRe")]
    [AllowAnonymous]
    public async Task<dynamic> LogRe(LogRec data)
    {
        await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"收到双发固件通行记录信息:{data.EmpName}", data.ClientSn, 0, 0, 0, "");
        try
        {
            if (string.IsNullOrWhiteSpace(data.EmpID)) throw Oops.Oh("人员ID不能为空");
            if (string.IsNullOrWhiteSpace(data.ClientSn)) throw Oops.Oh("设备ID不能为空");
            var device = await _deviceRep.GetFirstAsync(u => u.ClientSn == data.ClientSn) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
            UploadLog SaveEmpLog = new UploadLog();
            SaveEmpLog.ClientSn = data.ClientSn;
            SaveEmpLog.EmpSn = data.EmpID;
            SaveEmpLog.EmpName = data.EmpName;
            SaveEmpLog.cap_time = data.cap_time;
            SaveEmpLog.ImageBase64 = data.ImageBase64;
            SaveEmpLog.IsUpload = true;
            SaveEmpLog.IsUploadErr = false;
            SaveEmpLog.ErrorMsg = "";
            SaveEmpLog.ProjectId = device.ProjectId;
            SaveEmpLog.TenantId = device.TenantId;
            SaveEmpLog.CreateOrgId = device.CreateOrgId;
            SaveEmpLog.CreateTime = DateTime.Now;
            await _uploadLogRep.InsertAsync(SaveEmpLog);
            //await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"收到双发固件通行记录信息:{data.EmpName}", data.ClientSn, 0, 0, 0, "");
            return "接收正常";
        }
        catch (Exception)
        {
            await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"收到双发固件通行记录信息:{data.EmpName}", data.ClientSn, 0, 0, 0, "");
            throw Oops.Oh("异常");
        }
    }

    /// <summary>
    /// 移动打卡数据补录
    /// </summary>
    /// <param name="ClientSn">设备号</param>
    /// <returns></returns>
    [HttpGet("other/SendEmpLog")]
    [AllowAnonymous]
    public async Task<LogRec> SendEmpLog(string ClientSn)
    {
        if (string.IsNullOrWhiteSpace(ClientSn)) throw Oops.Oh("设备ID不能为空");
        var device = await _deviceRep.GetFirstAsync(u => u.ClientSn == ClientSn) ?? throw Oops.Oh(ErrorCodeEnum.D1002);

        var Log = await _uploadLogRep.AsQueryable()
             .ClearFilter()
             .Where(u => u.ClientSn == ClientSn && u.IsUpload == false && (int)u.AuditingStatus == 1 && u.IsMobile == true)
             .FirstAsync();
        if (Log == null) throw Oops.Oh("暂无记录");

        var EmpLog = new LogRec();
        EmpLog.ClientSn = ClientSn;
        EmpLog.EmpID = Log.EmpSn;
        EmpLog.EmpName = Log.EmpName;
        EmpLog.Direction = (int)device.Direction;
        EmpLog.IdCardNum = "";
        EmpLog.cap_time = Log.cap_time;
        EmpLog.ImageBase64 = Log.ImageBase64;

        //更新
        await zJLog.LogPlat(LogLevel.Information, LogType.Error, $"双发固件取补录信息:{Log.EmpName}", ClientSn, 0, 0, 0, "");
        var updateLog = EmpLog.Adapt<UploadLog>();
        Log.IsUpload = true;
        await _uploadLogRep.UpdateAsync(Log);
        return EmpLog;
    }
}

public class EmpRec
{
    /// <summary>
    /// 客户端设备号
    /// </summary>
    [Required(ErrorMessage = "客户端设备号不能为空")]
    public virtual string ClientSn { get; set; }

    /// <summary>
    /// 人员ID
    /// </summary>
    [Required(ErrorMessage = "人员ID不能为空")]
    public virtual string EmpID { get; set; }

    /// <summary>
    /// 自定义的字段信息，用于UUID
    /// </summary>
    public string customer_text { get; set; }

    /// <summary>
    /// 姓名
    /// </summary>
    public virtual string Name { get; set; }

    /// <summary>
    /// 年龄
    /// </summary>
    public virtual int Age { get; set; }

    /// <summary>
    /// 工种
    /// </summary>
    public virtual string Category { get; set; }

    /// <summary>
    /// 人脸图片Base64
    /// </summary>
    public virtual string ImageBase64 { get; set; }

    /// <summary>
    /// 性别
    /// </summary>
    public virtual GenderEnum Sex { get; set; }

    /// <summary>
    /// 工作组
    /// </summary>
    public virtual string Work_TypeName { get; set; }

    /// <summary>
    /// 身份证号
    /// </summary>
    public virtual string IdNum { get; set; }

    /// <summary>
    /// 民族
    /// </summary>
    public virtual string Nation { get; set; }

    /// <summary>
    /// 生日
    /// </summary>
    public virtual string Birthday { get; set; }

    /// <summary>
    /// 住址
    /// </summary>
    public virtual string Address { get; set; }

    /// <summary>
    /// 户籍
    /// </summary>
    public virtual string Native { get; set; }

    /// <summary>
    /// 电话
    /// </summary>
    public virtual string Phone { get; set; }

    /// <summary>
    /// 紧急联系人
    /// </summary>
    public virtual string EmerPeople { get; set; }

    /// <summary>
    /// 紧急联系人电话
    /// </summary>
    public virtual string EmerPhone { get; set; }

    /// <summary>
    /// 文化程度
    /// </summary>
    public virtual int Culture { get; set; }

    /// <summary>
    /// 健康状况
    /// </summary>
    public virtual int Health { get; set; }

    /// <summary>
    /// 签发机关（长度20个字符）
    /// </summary>
    public virtual string QianFaJiGuan { get; set; }

}

public class LogRec
{
    /// <summary>
    /// 客户端设备号
    /// </summary>
    [Required(ErrorMessage = "客户端设备号不能为空")]
    public virtual string ClientSn { get; set; }

    /// <summary>
    /// 人员ID
    /// </summary>
    [Required(ErrorMessage = "人员ID不能为空")]
    public virtual string EmpID { get; set; }

    /// <summary>
    /// 自定义的字段信息，用于UUID
    /// </summary>
    public string customer_text { get; set; }

    /// <summary>
    /// 人员姓名
    /// </summary>
    public string EmpName { get; set; }

    /// <summary>
    /// 身份证号
    /// </summary>
    public string IdCardNum { get; set; }

    /// <summary>
    /// 0进，1出  进出标志
    /// </summary>
    public int Direction { get; set; }

    /// <summary>
    /// 抓拍时间
    /// </summary>
    public string cap_time { get; set; }

    /// <summary>
    /// 通行图片Base64
    /// </summary>
    public string ImageBase64 { get; set; }
}